<?php

namespace App\Module\Api\Controllers;
use App\Exceptions\Customize\ParamsException;
use App\Module\Api\Controllers\Request\UserRegisterRequest;
use App\Module\Api\Validator\UserRegisterValidator;
use App\System\Base\Services\TokenService;
use App\System\Cis\Repositories\CisUserRepository;
use App\System\Cis\Services\DeclarationInputValidationService;
use App\System\Cis\Services\DeclarationStorageService;

/**
 * 用户报单
 * @package App\Module\Admin\Controllers
 */
class UserRegisterController extends Controller
{

    public function __construct()
    {
        $this->query = new UserRegisterRequest();
        parent::__construct();

    }

    public function index()
    {
        (new UserRegisterValidator())->check();
        $user_id = TokenService::getUserId();
        $query = $this->query;
        $user = CisUserRepository::getInstance();
        $user_info = $user->getUser($user_id,2);
        if(!$user_info)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '非城市合伙人角色不允许报单',
            ]);
        }

        $input = new DeclarationInputValidationService();
        $input->generatingNumber = $query->number ;
        $input->cityPartnerId = $user_id;
        $input->recommendId = $query->referrerId;
        $input->market =$query->type;
        $input->accountOwnerMobile = $query->mobile;
        $input->userInformationVerification();
        if(!$input->getErrorMsg())
        {
            $res = new DeclarationStorageService($input);
            $res->getDeclarationResult();
            if($res->getErrorMsg())
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => $res->getErrorMsg(),
                ]);
            }
            $user_ids = $res->getUserIds();
            $number = count($user_ids);
            if($number > 1){
                $user_ids = implode("-",$user_ids);
            }
            else
            {
                $user_ids = $user_ids[0];
            }
            return apiResponse(['ids'=>$user_ids]);
        }
        else
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => $input->getErrorMsg(),
            ]);
        }

    }
}
